package cn.com.dhcc.ddi.stat.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.pubmodule.sysmgr.usermgr.service.CmUserMgrService;
import cn.com.dhcc.app.core.pubmodule.sysmgr.usermgr.vo.UserInfoVo;
import cn.com.dhcc.app.core.util.StrUtil;
import cn.com.dhcc.app.pub.core.util.dateformatter.DateFormatter;
import cn.com.dhcc.ddi.datamapping.service.DataMappingService;
import cn.com.dhcc.ddi.stat.service.DataSyncStatService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.ddi.stat.service.TaskSyncStatService;
import cn.com.dhcc.ddi.stat.vo.CalendarEventVo;
import cn.com.dhcc.ddi.stat.vo.TaskSyncStatVo;
import cn.com.dhcc.ddi.task.service.TaskService;
import cn.com.dhcc.ddi.task.vo.Task;

import javax.servlet.http.HttpSession;

/**
 * 
    * @ClassName: TaskCalendarController
    * @date 2017-3-10
    *
 */
@Controller
@RequestMapping("/stat")
public class TaskCalendarController extends BaseController {

 Logger logger = Log.getLogger(LOGTYPE.ADAPTER);
	
	@Autowired
	private TaskSyncStatService taskSyncStatService;
	@Autowired
	private TaskService taskService;

	@Autowired
	CmUserMgrService userMgrService;
	@Autowired
	DataMappingService dataMappingService;
	/**
	 * 获取列表
	    * @Title: list
	    * @Description: TODO(这里用一句话描述这个方法的作用)
	    * @param @param model
	    * @param @param pager
	    * @param @param name
	    * @param @param orderName
	    * @param @param order
	    * @param @return    参数
	    * @return String    返回类型 
	    * @throws
	 */
	@RequestMapping(value = "/taskCalenda_info_list")
	public String list(Model model, Pager pager, String statDate,String taskId,HttpSession httpSession) {
		try {
			WhereCondition condition = new WhereCondition();
			WhereCondition dataCondition = new WhereCondition();
			Boolean isAdmin = BaseController.getCurrentUserInfo(httpSession).isSuperAdmin();
			String userId = BaseController.getCurrentUserInfo(httpSession).getId();
			if(!isAdmin){
				condition.where();
				UserInfoVo currentUser = userMgrService.getUserById(userId);
				if(currentUser != null){
					String nodeIdsStr = currentUser.getExt2();
					WhereCondition dmParameter = new WhereCondition();
					dmParameter.where();
					if(StrUtil.isNotBank(nodeIdsStr)){
						String[] nodeIds = nodeIdsStr.split(",");
						dmParameter.in("t2.node_id", nodeIds);
						dmParameter.andIn("t3.node_id", nodeIds);
					}else{
						dmParameter.eq("1", "2");
					}
					List<String> dmids = dataMappingService.getDmid(dmParameter);
					//过滤用户数据
					if (dmids!=null && dmids.size()>0){
						condition.in("mp_id",dmids);
						dataCondition.and().in("t2.mp_id",dmids);
					}else {
						condition.eq("1","2");
						dataCondition.and().eq("1","2");
					}
				}
			}
			List<Task> tasks = taskService.getTaskList(condition);
			model.addAttribute("tasks", tasks);
			if(taskId != null && taskId.equals("all")) {
				taskId = null;
			}
			if(statDate == null) {
				statDate = DateFormatter.getDateBasedOnToday("yyyy-MM-dd", -1);
			}
			PagerData<TaskSyncStatVo> datas = taskSyncStatService.getCalendarPagerData(pager, dataCondition, statDate, taskId);
			/*WhereCondition searchData = new WhereCondition();
			if (StrUtil.isNotBlank(taskName)) {
				searchData.where().like("taskName", "%"+taskName+"%");
			}
			if (StrUtil.isNotBlank(taskId)) {
				searchData.and().eq("t1.task_id" , taskId);
			}
			if (StrUtil.isNotBlank(statDate)) {
				searchData.and().like("t1.stat_date","%"+statDate+"%");
			}
			if (StrUtil.isNotBlank(orderName)) {
				searchData.orderBy(orderName + " " + order);
			} else {
				searchData.orderBy("task_id  desc");
			}
			PagerData<TaskSyncStatVo> datas = taskSyncStatService.list(pager, searchData);*/
			model.addAttribute(DATA_KEY, datas.getDatas());
			setTotoal(model, datas.getTotal());
			return "stat/task_calendar_list";
		} catch (Exception e) {
			logger.error("操作失败", e);
			return toAlertPage(model, e.getMessage());
		}
	}
	
	/**
	 * 转到各任务数据量统计图页面
	 * @param 
	 * @return
	 * @throws 
	 */
	@RequestMapping("/task_calendar")
	public String recSentChart(Model model,HttpSession httpSession) {
		try {
			WhereCondition condition = new WhereCondition();
			Boolean isAdmin = BaseController.getCurrentUserInfo(httpSession).isSuperAdmin();
			String userId = BaseController.getCurrentUserInfo(httpSession).getId();
			if(!isAdmin){
				condition.where();
				UserInfoVo currentUser = userMgrService.getUserById(userId);
				if(currentUser != null){
					String nodeIdsStr = currentUser.getExt2();
					WhereCondition dmParameter = new WhereCondition();
					dmParameter.where();
					if(StrUtil.isNotBank(nodeIdsStr)){
						String[] nodeIds = nodeIdsStr.split(",");
						dmParameter.in("t2.node_id", nodeIds);
						dmParameter.andIn("t3.node_id", nodeIds);
					}else{
						dmParameter.eq("1", "2");
					}
					List<String> dmids = dataMappingService.getDmid(dmParameter);
					//过滤用户数据
					if (dmids!=null && dmids.size()>0){
						condition.in("mp_id",dmids);
					}else {
						condition.eq("1","2");
					}
				}
			}
			List<Task> tasks = taskService.getTaskList(condition);
			model.addAttribute("tasks", tasks);
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "stat/task_calendar";
	}
	
	
	/**
	 * 转到各任务频次统计图页面
	 * @param 
	 * @return
	 * @throws 
	 *//*
	@RequestMapping("/task_calendar_total")
	public String totalSentChart() {
		return "stat/task_syn_total";
	}*/
	
	/**
	 * 获取日历数据
	 * @param start  开始时间
	 * @param end    结束时间
	 * @param taskId 任务id
	 * @param type 统计类型 0-频次 1-数据量
	 * @return
	 */
	@RequestMapping("/get_cal_data")
	@ResponseBody
	public Map<String,Object> getCalendarData(String start, String end, String taskId, String type,HttpSession httpSession) {
		try {			
			if(taskId.equals("all")) {
				taskId  = null;
			}
			WhereCondition condition = new WhereCondition();
			Boolean isAdmin = BaseController.getCurrentUserInfo(httpSession).isSuperAdmin();
			String userId = BaseController.getCurrentUserInfo(httpSession).getId();
			if(!isAdmin){
				UserInfoVo currentUser = userMgrService.getUserById(userId);
				if(currentUser != null){
					String nodeIdsStr = currentUser.getExt2();
					WhereCondition dmParameter = new WhereCondition();
					dmParameter.where();
					if(StrUtil.isNotBank(nodeIdsStr)){
						String[] nodeIds = nodeIdsStr.split(",");
						dmParameter.in("t2.node_id", nodeIds);
						dmParameter.andIn("t3.node_id", nodeIds);
					}else{
						dmParameter.eq("1", "2");
					}
					List<String> dmids = dataMappingService.getDmid(dmParameter);
					//过滤用户数据
					if (dmids!=null && dmids.size()>0){
						condition.and().in("t2.mp_id",dmids);
					}else {
						condition.and().eq("1","2");
					}
				}
			}
			condition.groupBy("DATE(t1.stat_date) ");
			List<TaskSyncStatVo> datas = taskSyncStatService.getCalendarData(start, end, taskId,condition);
			List<Integer> values = new ArrayList<Integer>();
			
			
			for(TaskSyncStatVo vo: datas) {
				if(type.equals("0")) {
					values.add(vo.getTotal());					
				} else {
					values.add(vo.getDataSize());					
				}
			}
			
			//如果list不为空，标记最大值
			List<CalendarEventVo> events = new ArrayList<CalendarEventVo>();
			if(values.size() != 0) {
				Integer max = Collections.max(values);
				for(TaskSyncStatVo vo: datas) {
					String title = "";
					Boolean isMax = false;
					if(type.equals("0")) {
						title = vo.getTotal() + "";
						if(vo.getTotal() == max && max != 0) {
							isMax = true;
						}
					} else {
						title = vo.getDataSize() + "";
						if(vo.getDataSize() == max && max != 0) {
							isMax = true;
						}
					}
					CalendarEventVo event = new CalendarEventVo(title, vo.getStatDate(), isMax);
					events.add(event);
				}
			}
			
			
			
			return jsonSuccessDataResult("获取日历数据", events);
		} catch(ServiceException e) {
			logger.error(e);
			return jsonFailResult("获取日历数据失败");
		}
	}
}
